package com.uk.ui.tarifa;

import java.util.Arrays;
import java.util.List;

import com.uk.HandleMessages;
import com.uk.data.containers.TarifaContainer;
import com.uk.data.entities.Kontrata;
import com.uk.data.entities.StatusEnum;
import com.uk.data.entities.Tarifa;
import com.uk.exceptions.NestedException;
import com.vaadin.data.Item;
import com.vaadin.data.util.BeanItem;
import com.vaadin.terminal.UserError;
import com.vaadin.ui.Button;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.Field;
import com.vaadin.ui.Form;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Select;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.DefaultFieldFactory;


public class TarifaForm  extends Form implements ClickListener{

	
	private Button save = new Button("Ruaj", (ClickListener) this);
	private Button cancel = new Button("Anullo", (ClickListener) this);
	private Button edit = new Button("Ndrysho", (ClickListener) this);
	
	
	private boolean addTarifaMode = false;
	private Tarifa newTarife = null;
	private TarifaPanel tarifaPanel;
	
	private final Select statusSelect;
	
	
	
	public TarifaForm(TarifaPanel tarifaPanel) {
		this.tarifaPanel = tarifaPanel;
		this.statusSelect = new Select("Statusi");
		this.statusSelect.addItem(StatusEnum.AKTIV);
		this.statusSelect.addItem(StatusEnum.JOAKTIVE);
		this.statusSelect.setImmediate(true);
		
		setWriteThrough(false);
		this.setInvalidCommitted(false);
		HorizontalLayout footer = new HorizontalLayout();
		footer.setSpacing(true);
		footer.addComponent(save);
		footer.addComponent(cancel);
		footer.addComponent(edit);
		footer.setVisible(false);
		setFooter(footer);
		

		setFormFieldFactory(new DefaultFieldFactory(){

			/**
			 * 
			 */
			private static final long serialVersionUID = 4459631256682498031L;
			
			@Override
			public Field createField(Item item, Object propertyId,
					Component uiContext) {
				
				Field field = super.createField(item, propertyId, uiContext);
				
				if(propertyId.equals("kodi")){
					TextField tf = (TextField) field;
					tf.setMaxLength(5);
					tf.setRequired(true);
		            tf.setRequiredError("Kodi nuk duhet te jete bosh!");
					tf.setWidth("200px");
					tf.setNullRepresentation("");
					return tf;
					
				}
				if(propertyId.equals("pershkrimi")){
					TextField tf = (TextField) field;
					tf.setMaxLength(100);
					tf.setRequired(true);
		            tf.setRequiredError("Pershkrimi nuk duhet te jete bosh!");
					tf.setWidth("200px");
					tf.setNullRepresentation("");
					return tf;
				}
				
				if(propertyId.equals("njesia")){
					TextField tf = (TextField) field;
					tf.setMaxLength(10);
					tf.setRequired(true);
		            tf.setRequiredError("Njesia nuk duhet te jete bosh!");
					tf.setWidth("200px");
					tf.setNullRepresentation("");
					return tf;
				}
				if(propertyId.equals("cmimi")){
					TextField tf = (TextField) field;
					tf.setWidth("200px");
					tf.setNullRepresentation("0.00");
					return tf;		
				}
				if(propertyId.equals("aplikoTVSH")){
					CheckBox ch = (CheckBox)field;
					ch.setCaption("Apliko TVSH?");
					return ch;
				}
				if (propertyId.equals("status")){
					statusSelect.setWidth("200px");
					statusSelect.setImmediate(true);
					statusSelect.setRequired(true);
					statusSelect.setRequiredError("Statusi nuk duhet te jete bosh!");
					return statusSelect;
				}
				
				if (propertyId.equals("uk")){
					CheckBox ch = (CheckBox)field;
					ch.setCaption("Tarife e ujesjellesit?");
					return ch;
				}
				
				if (propertyId.equals("neListe")){
					CheckBox ch = (CheckBox)field;
					ch.setCaption("Ne liste?");
					return ch;
				}
				 return null;
				
			}
		});
		
	}

	public void setItemDataSource(Item newDataSource){
		addTarifaMode = false;
		this.setVisible(true);
		if (newDataSource != null){
			setReadOnly(false);
			List<Object> orderedProperties = Arrays.asList(TarifaContainer.COL_ORDER_FOR_FORM);
			super.setItemDataSource(newDataSource, orderedProperties);
			setReadOnly(true);
			getFooter().setVisible(true);
		}
		else{
			super.setItemDataSource(null);
			this.setVisible(false);
			getFooter().setVisible(false);
		}
		
	}
	
	
	public void setReadOnly(boolean readOnly){
		super.setReadOnly(readOnly);
		save.setVisible(!readOnly);
		cancel.setVisible(!readOnly);
		edit.setVisible(readOnly);
	}
	
	public void addTarife() {
		newTarife = new Tarifa();
		setItemDataSource(new BeanItem<Tarifa>(newTarife));
		addTarifaMode = true;
		setReadOnly(false);
		this.getField("status").setValue(StatusEnum.AKTIV);
		this.getField("status").setReadOnly(true);
		
	}

	@Override
	public void buttonClick(ClickEvent event) {
		Button source = event.getButton();
		this.setComponentError(null);
		try {
			if (source == save){
				try {
					if (addTarifaMode)
						if (!tarifaPanel.getFaturaBean().isTarifaCodeUnique(this.getField("kodi").toString())){
							this.setComponentError(new UserError("Kodi i kesa tarife ekziston ne databaze. Zgjidhni nje kod tjeter"));
							return;
						}
					
					setReadOnly(false);
					Tarifa tarifa = ((BeanItem<Tarifa>)this.getItemDataSource()).getBean().clone();
					commit();
					Tarifa afterCommit = ((BeanItem<Tarifa>)this.getItemDataSource()).getBean();

					if (addTarifaMode){
						newTarife = tarifaPanel.getFaturaBean().saveTarifa(afterCommit, false);
						Item addedItem = tarifaPanel.getDataSource().addItem(newTarife);
						setItemDataSource(addedItem);
						addTarifaMode = false;
					}
					else{
						
						if ((tarifa.getCmimi()!= afterCommit.getCmimi()) ||
								!tarifa.getNjesia().equals(afterCommit.getNjesia())){
							newTarife = tarifaPanel.getFaturaBean().saveTarifa(afterCommit, true);
							tarifaPanel.getDataSource().removeItem(tarifa);
							Item addedItem = tarifaPanel.getDataSource().addItem(newTarife);
							setItemDataSource(addedItem);
						}
						else{
							newTarife = tarifaPanel.getFaturaBean().saveTarifa(afterCommit, false);
						}
						
					}
					setReadOnly(true);
					HandleMessages.showInformationOnScree(HandleMessages.SUCCESS_SAVE, this);
				} catch (NestedException e) {
					HandleMessages.showErrorOnScreen(e, this);
				} catch (Exception e) {
					HandleMessages.showErrorOnScreen(e, this);
				}
			}
			else if (source == cancel){
				if (addTarifaMode){
					addTarifaMode = false;
					setItemDataSource(null);
				}
				else {
					discard();
				}
				setReadOnly(true);
			}
			else if ( source == edit){
				setReadOnly(false);
				this.getField("kodi").setReadOnly(true);
			}
	
		} catch (Exception e) {
			HandleMessages.showErrorOnScreen(e, this);
		}
		
	}

	
	
	private void test() throws CloneNotSupportedException{
		Tarifa tarifa = ((BeanItem<Tarifa>)this.getItemDataSource()).getBean().clone();
		commit();
		Tarifa afterCommit = ((BeanItem<Tarifa>)this.getItemDataSource()).getBean();
		boolean isDifferent = false;
		if ((tarifa.getCmimi()!= afterCommit.getCmimi()) ||
				!tarifa.getNjesia().equals(afterCommit.getNjesia())){
			newTarife = tarifaPanel.getFaturaBean().saveTarifa(afterCommit, true);	
		}
		else{
			newTarife = tarifaPanel.getFaturaBean().saveTarifa(afterCommit, false);
		}
			
		
	}
}
